#!/usr/bin/python3
# -*- coding: utf-8 -*-
import requests
import re
import json
from flask import Flask,make_response,render_template,request

def get_link(share_link):
    temp = share_link.split("com/")[1].split("/")[0]
    share_url = "https://v.douyin.com/"+temp
    headers = {
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'}
    r = requests.get(share_url,headers)
    # 获取ID
    item_ids =r.url.split("?")[0].split("video/")[1]
    base_url='https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids='+item_ids
    video_info = get_video_info(item_ids)

    if not video_info:
        print("视频信息获取失败，可能链接已失效")
        exit()

    # 提取视频地址
    video_url = video_info['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['video']['play_addr']['url_list'][0]

    video_url = video_url.replace('playwm', 'play')


    # 获取无水印下载链接

    video = requests.get(video_url,headers)
    # print(video.headers)
    # with open(item_ids+".mp4","wb") as f:
    #     f.write(video.content)

    return video.content,item_ids

app = Flask(__name__)

@app.route("/douyin",methods=["POST","GET"])
def douyin():
    if request.method=="POST":
        result=request.form

    video,filename=get_link(result["share_link"])
    print(filename)
    response = make_response(video) #将video字节流封装成response对象

    # 添加响应头部信息
    response.headers['Content-Type'] = "video/mp4"
    # attachment表示以附件形式下载
    response.headers['Content-Disposition'] = 'attachment; filename='+filename+'.mp4'
    return response

@app.route("/",methods=["POST","GET"])
def index():
    return render_template("index.html")

def get_video_info(item_id):
    """获取视频信息"""
    api_url = f"https://www.iesdouyin.com/share/video/{item_id}"

    headers = {
        'Referer': 'https://www.douyin.com/',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
    }



    try:
        response = requests.get(api_url, headers=headers, verify=False, timeout=10)
        if response.status_code != 200:
            return None

        res = response.text
        title = re.findall('<title[^>]*>(.*?)</title>', res)[0]
        print("title", title)

        data = re.findall('_ROUTER_DATA\s*=\s*({.*?});',res)[0]
        info = json.loads(data)
        # url = info['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['video']['play_addr']['url_list'][0]
        # if data.get('status_code') != 0:
        #     return None

        return info
    except Exception as e:
        print("获取视频信息失败:", str(e))
        return None


if __name__ == "__main__":
    app.run(debug=False, host="0.0.0.0",port=3000)